package com.example.teaching_server.entity;

import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 活动实体类
 */
@Getter
@Setter
@ToString(exclude = {"base", "creator", "checkins", "participants"})
@EqualsAndHashCode(of = "id")
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "activities", indexes = {
        @Index(name = "idx_start_date", columnList = "start_date"),
        @Index(name = "idx_creator_id", columnList = "creator_id")
})
public class ActivityEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    @NotBlank(message = "活动标题不能为空")
    private String title;

    @Column(length = 2000)
    private String description;

    @Column(name = "start_date", nullable = false)
    @NotNull(message = "开始日期不能为空")
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate startDate;

    @Column(name = "end_date", nullable = false)
    @NotNull(message = "结束日期不能为空")
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate endDate;

    @Column(name = "total_days")
    private Integer totalDays;

    @Column(name = "base_id")
    private Long baseId;

    @Column(name = "base_name")
    private String baseName;

    private String address;

    @Column(name = "start_time")
    @JsonFormat(pattern = "HH:mm:ss")
    private LocalTime startTime;

    @Column(name = "registration_deadline")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime registrationDeadline;

    @Column(name = "target_audience")
    private String targetAudience;

    @Column(name = "is_free")
    @Builder.Default
    private Boolean isFree = true;

    @Column(name = "publish_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime publishTime;

    @CreationTimestamp
    @Column(name = "created_at", updatable = false)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createdAt;

    @UpdateTimestamp
    @Column(name = "updated_at")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updatedAt;

    @Column(name = "max_participants")
    private Integer maxParticipants;

    @Column(name = "current_participants")
    @Builder.Default
    private Integer currentParticipants = 0;

    @Column(name = "creator_id")
    private Long creatorId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "base_id", insertable = false, updatable = false)
    private ActivityBaseEntity base;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "creator_id", insertable = false, updatable = false)
    private UserEntity creator;

    @OneToMany(mappedBy = "activity", cascade = CascadeType.ALL)
    private List<ActivityCheckinEntity> checkins;

    @OneToMany(mappedBy = "activity", cascade = CascadeType.ALL)
    private List<ActivityParticipantEntity> participants;

    @Transient
    public boolean isRegistrationOpen() {
        if (registrationDeadline == null) {
            return true;
        }
        return LocalDateTime.now().isBefore(registrationDeadline);
    }

    @Transient
    public boolean hasAvailableSlots() {
        if (maxParticipants == null) {
            return true;
        }
        return currentParticipants < maxParticipants;
    }

    @PrePersist
    @PreUpdate
    private void validateDates() {
        if (endDate != null && startDate != null && endDate.isBefore(startDate)) {
            throw new IllegalArgumentException("结束日期不能早于开始日期");
        }
        if (registrationDeadline != null && startDate != null &&
                registrationDeadline.toLocalDate().isAfter(startDate)) {
            throw new IllegalArgumentException("报名截止日期不能晚于活动开始日期");
        }
    }
}
